package com.econ.powercloud.ems.util;

import com.econ.powercloud.common.base.facade.enums.StatusType;
import com.econ.powercloud.common.base.facade.exception.CommonRuntimeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.util.UriUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;

/**
 * @Author : zjf
 * @Description :
 * @Date : 2023/6/2 10:55
 * @Modified by : zjf
 */
@Slf4j
public class DownLoadFileUtils {
    private DownLoadFileUtils() {
    }

    public static void downLoad(String filePath, String fileName, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        File file=new File(filePath);
        //如果不是文件
        if (!file.exists()) {
            throw new CommonRuntimeException(StatusType.FAIL,"文件不存在！");
        }
        String suffix = filePath.substring(filePath.lastIndexOf("."));
        fileName += suffix;
        response.setContentType("application/octet-stream");
        OutputStream os = null;
        FileInputStream fileInputStream = null;
        DataInputStream dataInputStream = null;
        try {
            response.setHeader("Content-disposition","attachment;filename="+ UriUtils.encode(fileName, Charset.defaultCharset().name()));
            os = response.getOutputStream();
            fileInputStream = new FileInputStream(file);
            dataInputStream = new DataInputStream(fileInputStream);
            int r;
            while((r=dataInputStream.read())!=-1) {
                os.write(r);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(dataInputStream != null){
                    dataInputStream.close();
                }
                if(fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
